#! /usr/bin/env python
"""\
Scan for serial ports.

Part of pySerial (http://pyserial.sf.net)
(C) 2002-2003 <cliechti@gmx.net>

The scan function of this module tries to open each port number
from 0 to 255 and it builds a list of those ports where this was
successful.
"""

import serial

def read_response(device):
    response = b''
    while True:
        char = device.read()
        if char == b'' or char == b'\r':
            return response
        response += char

def scan():
    """scan for available ports. return a list of tuples (num, name)"""
    available = []
    for i in range(256):
        try:
            s = serial.Serial(i, baudrate=19200, timeout=1)
            def get_resp():
                resp = b''
                while True:
                    char = s.read()
                    print(repr(char))
                    if char == b'': return resp
                    resp += char

            print("There is port {}, trying".format(i))
            #s.write(b'S\r')
            #resp = get_resp()
            #print("yes, it responded {!r}".format(resp))
            s.write(b'X\r')
            resp = get_resp()
            print(repr(resp))
            if not resp: continue
            s.write(b'M\r')
            print(repr(get_resp()))
            available.append( (i, s.portstr))
            s.write(b'S\r')
            res = read_response(s)
            if res:
                print("discharger on port {}. Response was {}".format(i, res))
            s.write(b'S\r')
            res = read_response(s)
            if res:
                print("charger on port {}. Response was {}".format(i, res))
            s.close()   # explicit close 'cause of delayed GC in java
        except serial.SerialException:
            pass
    return available

if __name__=='__main__':
    print("Found ports:")
    for n,s in scan():
        print("(%d) %s" % (n,s))
    